<?php
class Articles extends MY_Model{
    public function __construct() {
        parent::__construct();
    }
    //insert post
    public function add_article($fields=array()){   
        if(empty($fields)){
            return false;
        }
        $this->db->insert('posts',$fields);
        return $this->db->insert_id();
    }
    
    //get post of category
    public function get_article_by_category($cate_id= false,$limited=false,$page=10,$type=false)
    {
        $this->db->order_by('post_id','desc');
		//$this->db->where('valid'=>1);
        if($cate_id){
            $this->db->where(array('cat_id'=>$cate_id));
        }
        if($limited===false){
            
        }else{
            $this->db->limit($page,$limited*10);}
        if($type)
            $this->db->where('type',$type);
		    $this->db->where('valid',1);
        $query = $this->db->get('posts');
       
        return $query->result();
    }
    
    //get posts
    public function get_article($post_id=false){
        
        $condition = array();
        if($post_id){
            $condition = array('post_id'=>$post_id,'valid'=>1);
            //$this->db->where(array('post_id'=>$post_id,'valid'=>0));
        }else{
            $condition = array('valid'=>1);
        }
        
        $query = $this->db->get_where('posts',$condition);
        if($post_id){
            return $query->row();
        }
        return $query->result();
    }
    
    public function get_feature_article($cat_id = false)
    {
        if($cat_id){
            $this->db->where('cat_id',$cat_id);
            $this->db->limit(5);
        $this->db->where('feature >',1);
        $this->db->where('valid',1);
        $this->db->order_by('post_id','desc');
        return $this->db->get('posts')->result();
        }else{
            $sql = 'select * from posts where  feature=1 and valid=1 order by rand() limit 5';
            
            $query = $this->db->query($sql);
            return $query->result();
        }
        
        
    }
    
    //update post
    public function update_article($field=array(),$condition=array()){
        if(empty($field)||empty($condition))
            return false;
        $this->db->update('posts',$field,$condition);
        return $this->db->affected_rows();
    }
    
    public function delete_article($post_id = false){
        if($post_id){
            $this->db->where('post_id',$post_id);
            $this->db->update('posts',array('valid'=>0));
        }        
        return $this->db->affected_rows();
    }
}
?>